package com.zh.zookeeper;

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;


public class ZkTest {

	public static String url = "andSys.com:2181";
	
    public static String root  = "/zk";
    
    public static String child  = "/zk/child1";

	public static void main(String[] args) {

		try {
			ZooKeeper zKeeper = new ZooKeeper(url, 3000, new Watcher() {

				public void process(WatchedEvent event) {
					System.out.println("触发了事件:" + event.getType());
					System.out.println("事件状态:" + event.getState());
				}

			});

			System.out.println("zk status:" + zKeeper.getState());

			while (!"CONNECTED".equals(zKeeper.getState().toString())) {
				Thread.sleep(3000);
			}
			if(null==zKeeper.exists(root, true)){
				zKeeper.create(root, "root".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			}
			if(null==zKeeper.exists(child, true)){
				zKeeper.create(child, "child".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
			}
			String rootdata = new String(zKeeper.getData(root, true, null));
			System.out.println("root data is:"+ rootdata);
			
			zKeeper.setData(root, "rootupdate1".getBytes(), -1);
		    rootdata = new String(zKeeper.getData(root, true, null));
			System.out.println("root data is:"+ rootdata);
			System.out.println("getChildren  is:"+ zKeeper.getChildren(root, true));
			
			
			System.out.println("-------------------------------");
			System.out.println("child data is:"+ new String(zKeeper.getData(child, false, null)));
			zKeeper.setData(child, "child1update".getBytes(), -1);
			System.out.println("child data is:"+ new String(zKeeper.getData(child, true, null)));

			zKeeper.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeeperException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
